/**
 * created by dqn
 * 2018/4/12--23:26
 */

package me.dqn.noway.util;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import me.dqn.noway.bean.PasswordInformation;
import me.dqn.noway.bean.PasswordUser;

/**
 * 数据加密类
 */
public class DesEncryptor {

    // des 算法
    public static final String ALGORITHM = "DES";
    // 单例模式
    public static DesEncryptor INSTANCE = null;

    private DesEncryptor() {
    }

    public static DesEncryptor getIstance() {
        if (INSTANCE == null) {
            synchronized (DesEncryptor.class) {
                if (INSTANCE == null) {
                    INSTANCE = new DesEncryptor();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] decrypt(byte[] data, String key) throws Exception {
        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(key.getBytes());
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        // 真正开始解密操作
        return cipher.doFinal(data);
    }

    /**
     * 加密
     *
     * @param data
     * @param key
     * @return
     */
    public byte[] encrypt(byte[] data, String key) {
        try {

            SecureRandom random = new SecureRandom();

            DESKeySpec desKey = new DESKeySpec(key.getBytes());
            //创建一个密匙工厂，然后用它把DESKeySpec转换成
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            SecretKey securekey = keyFactory.generateSecret(desKey);
            //Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            //用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            //现在，获取数据并加密
            //正式执行加密操作
            return cipher.doFinal(data);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public String bytesToHexString(byte[] data) {
        char[] hexArray = "0123456789ABCDEF".toCharArray();
        char[] hexChars = new char[data.length * 2];
        for (int j = 0; j < data.length; j++) {
            int v = data[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    public byte[] hexStringToBytes(String hexString) {
        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hexString.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }


    /**
     * 加密数据
     *
     * @param passwordUser
     * @throws Exception
     */
    public PasswordInformation encryptData(PasswordUser passwordUser, PasswordInformation info) throws Exception {
        PasswordInformation passwordInformation = new PasswordInformation();
        passwordInformation.setUsername(bytesToHexString(encrypt(info.getUsername().getBytes(), passwordUser.getDecryptKey())));
        passwordInformation.setMail(bytesToHexString(encrypt(info.getMail().getBytes(), passwordUser.getDecryptKey())));
        passwordInformation.setType(bytesToHexString(encrypt(info.getType().getBytes(), passwordUser.getDecryptKey())));
        passwordInformation.setDetail(bytesToHexString(encrypt(info.getDetail().getBytes(), passwordUser.getDecryptKey())));
        passwordInformation.setPassword(bytesToHexString(encrypt(info.getPassword().getBytes(), passwordUser.getDecryptKey())));

        passwordInformation.setUserId(info.getUserId());

        return passwordInformation;
    }

    /**
     * 解密
     *
     * @param passwordUser
     * @throws Exception
     */
    public PasswordInformation decryptInformation(PasswordUser passwordUser, PasswordInformation info) throws Exception {
        PasswordInformation passwordInformation = new PasswordInformation();

        passwordInformation.setDetail(new String(decrypt(hexStringToBytes(info.getDetail()), passwordUser.getDecryptKey())));
        passwordInformation.setMail(new String(decrypt(hexStringToBytes(info.getMail()), passwordUser.getDecryptKey())));
        passwordInformation.setPassword(new String(decrypt(hexStringToBytes(info.getPassword()), passwordUser.getDecryptKey())));
        passwordInformation.setType(new String(decrypt(hexStringToBytes(info.getType()), passwordUser.getDecryptKey())));
        passwordInformation.setUsername(new String(decrypt(hexStringToBytes(info.getUsername()), passwordUser.getDecryptKey())));

        passwordInformation.setId(info.getId());
        passwordInformation.setUserId(info.getUserId());

        return passwordInformation;
    }
}
